<template>
  <div class="reason-library-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Collection /></el-icon>
          <div class="header-text">
            <h2>盘点差异原因库</h2>
            <p>管理盘点盈亏的常见原因，提高录入效率</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增原因
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计概览 -->
    <div class="stats-row">
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#409EFF"><Folder /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">原因总数</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#67C23A"><TrendCharts /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.profitReasons }}</div>
            <div class="stat-label">盘盈原因</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#F56C6C"><TrendCharts /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.lossReasons }}</div>
            <div class="stat-label">盘亏原因</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#E6A23C"><DataAnalysis /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.mostUsed }}</div>
            <div class="stat-label">最常使用</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true">
        <el-form-item label="类型">
          <el-select v-model="filterType" placeholder="全部类型" clearable style="width: 150px" @change="handleFilter">
            <el-option label="盘盈" value="profit" />
            <el-option label="盘亏" value="loss" />
            <el-option label="通用" value="common" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="filterCategory" placeholder="全部分类" clearable style="width: 150px" @change="handleFilter">
            <el-option label="管理问题" value="management" />
            <el-option label="系统问题" value="system" />
            <el-option label="人为失误" value="human" />
            <el-option label="商品质量" value="quality" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterStatus" placeholder="全部状态" clearable style="width: 120px" @change="handleFilter">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 原因列表 -->
    <el-card shadow="never">
      <el-table :data="filteredReasons" stripe border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="code" label="原因编码" width="120" />
        <el-table-column prop="name" label="原因名称" min-width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag type="info" plain>{{ getCategoryName(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageCount" label="使用次数" width="100" align="right" sortable>
          <template #default="{ row }">
            <el-tag type="primary" effect="plain">{{ row.usageCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.status" active-value="active" inactive-value="inactive" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)" size="small">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="success" @click="handleCopy(row)" size="small">
              <el-icon><CopyDocument /></el-icon>
              复制
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)" size="small">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="currentReason ? '编辑原因' : '新增原因'"
      width="600px"
      destroy-on-close
    >
      <el-form :model="reasonForm" :rules="reasonRules" ref="reasonFormRef" label-width="100px">
        <el-form-item label="原因编码" prop="code">
          <el-input v-model="reasonForm.code" placeholder="如：LOSS001" maxlength="20" />
        </el-form-item>
        <el-form-item label="原因名称" prop="name">
          <el-input v-model="reasonForm.name" placeholder="请输入原因名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="适用类型" prop="type">
          <el-radio-group v-model="reasonForm.type">
            <el-radio label="profit">盘盈</el-radio>
            <el-radio label="loss">盘亏</el-radio>
            <el-radio label="common">通用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因分类" prop="category">
          <el-select v-model="reasonForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="管理问题" value="management" />
            <el-option label="系统问题" value="system" />
            <el-option label="人为失误" value="human" />
            <el-option label="商品质量" value="quality" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细说明">
          <el-input v-model="reasonForm.description" type="textarea" :rows="3" placeholder="详细说明（选填）" />
        </el-form-item>
        <el-form-item label="解决方案">
          <el-input v-model="reasonForm.solution" type="textarea" :rows="3" placeholder="建议的解决方案（选填）" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="reasonForm.status" active-value="active" inactive-value="inactive" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 常用原因快速查看 -->
    <el-card shadow="never" class="popular-card" style="margin-top: 20px;">
      <div class="card-header">
        <div class="card-title">
          <el-icon><StarFilled /></el-icon>
          <span>常用原因TOP10</span>
        </div>
      </div>
      <div class="popular-list">
        <el-tag 
          v-for="reason in popularReasons" 
          :key="reason.id"
          :type="getTypeTag(reason.type)"
          size="large"
          style="margin: 4px;"
          effect="plain"
        >
          {{ reason.name }} ({{ reason.usageCount }}次)
        </el-tag>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Collection, Plus, Folder, TrendCharts, DataAnalysis, Edit,
  CopyDocument, Delete, StarFilled
} from '@element-plus/icons-vue'

// 状态
const showAddDialog = ref(false)
const reasonFormRef = ref(null)
const currentReason = ref(null)
const filterType = ref('')
const filterCategory = ref('')
const filterStatus = ref('')

// 统计数据
const stats = reactive({
  total: 45,
  profitReasons: 15,
  lossReasons: 25,
  mostUsed: '账实不符'
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 原因数据
const reasons = ref([
  {
    id: 1,
    code: 'LOSS001',
    name: '商品破损丢失',
    type: 'loss',
    category: 'quality',
    description: '商品在存储或搬运过程中发生破损或丢失',
    solution: '加强仓库管理，规范搬运流程',
    usageCount: 156,
    status: 'active',
    createTime: '2024-01-10 10:00:00'
  },
  {
    id: 2,
    code: 'LOSS002',
    name: '账实不符',
    type: 'loss',
    category: 'management',
    description: '系统记录与实际库存不一致',
    solution: '核查进出库记录，调整账面数据',
    usageCount: 245,
    status: 'active',
    createTime: '2024-01-10 10:05:00'
  },
  {
    id: 3,
    code: 'LOSS003',
    name: '销售未记录',
    type: 'loss',
    category: 'system',
    description: '商品已销售但系统未及时更新',
    solution: '检查收银系统，补录销售记录',
    usageCount: 89,
    status: 'active',
    createTime: '2024-01-10 10:10:00'
  },
  {
    id: 4,
    code: 'PROFIT001',
    name: '入库未记录',
    type: 'profit',
    category: 'system',
    description: '商品已入库但系统未及时记录',
    solution: '检查入库流程，补录入库单',
    usageCount: 78,
    status: 'active',
    createTime: '2024-01-10 10:15:00'
  },
  {
    id: 5,
    code: 'LOSS004',
    name: '商品过期报废',
    type: 'loss',
    category: 'quality',
    description: '商品超过保质期需要报废处理',
    solution: '加强先进先出管理，定期检查保质期',
    usageCount: 67,
    status: 'active',
    createTime: '2024-01-10 10:20:00'
  },
  {
    id: 6,
    code: 'LOSS005',
    name: '移库未记录',
    type: 'loss',
    category: 'management',
    description: '商品在仓库间调拨时未记录',
    solution: '规范调拨流程，及时记录单据',
    usageCount: 54,
    status: 'active',
    createTime: '2024-01-10 10:25:00'
  },
  {
    id: 7,
    code: 'COMMON001',
    name: '人工录入错误',
    type: 'common',
    category: 'human',
    description: '人工录入数据时发生错误',
    solution: '加强培训，启用双重核对机制',
    usageCount: 123,
    status: 'active',
    createTime: '2024-01-10 10:30:00'
  },
  {
    id: 8,
    code: 'PROFIT002',
    name: '退货未记录',
    type: 'profit',
    category: 'system',
    description: '客户退货商品未及时入库',
    solution: '完善退货流程，及时处理退货单',
    usageCount: 45,
    status: 'active',
    createTime: '2024-01-10 10:35:00'
  }
])

// 原因表单
const reasonForm = reactive({
  code: '',
  name: '',
  type: 'loss',
  category: '',
  description: '',
  solution: '',
  status: 'active'
})

// 表单验证规则
const reasonRules = {
  code: [{ required: true, message: '请输入原因编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入原因名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择适用类型', trigger: 'change' }],
  category: [{ required: true, message: '请选择原因分类', trigger: 'change' }]
}

// 计算属性
const filteredReasons = computed(() => {
  let result = reasons.value

  if (filterType.value) {
    result = result.filter(r => r.type === filterType.value)
  }

  if (filterCategory.value) {
    result = result.filter(r => r.category === filterCategory.value)
  }

  if (filterStatus.value) {
    result = result.filter(r => r.status === filterStatus.value)
  }

  pagination.total = result.length
  return result
})

const popularReasons = computed(() => {
  return reasons.value
    .filter(r => r.status === 'active')
    .sort((a, b) => b.usageCount - a.usageCount)
    .slice(0, 10)
})

// 方法
const handleFilter = () => {
  pagination.page = 1
}

const handleStatusChange = (row) => {
  ElMessage.success(`已${row.status === 'active' ? '启用' : '禁用'}`)
}

const handleEdit = (row) => {
  currentReason.value = row
  Object.assign(reasonForm, row)
  showAddDialog.value = true
}

const handleCopy = (row) => {
  currentReason.value = null
  Object.assign(reasonForm, {
    ...row,
    code: row.code + '_COPY',
    name: row.name + ' (复制)',
    usageCount: 0
  })
  showAddDialog.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该原因吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = reasons.value.findIndex(r => r.id === row.id)
    if (index > -1) {
      reasons.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

const handleSave = () => {
  reasonFormRef.value.validate((valid) => {
    if (valid) {
      if (currentReason.value) {
        // 更新
        Object.assign(currentReason.value, reasonForm)
        ElMessage.success('更新成功')
      } else {
        // 新增
        reasons.value.unshift({
          id: Date.now(),
          ...reasonForm,
          usageCount: 0,
          createTime: new Date().toLocaleString()
        })
        ElMessage.success('新增成功')
      }
      
      showAddDialog.value = false
      currentReason.value = null
      resetForm()
    }
  })
}

const resetForm = () => {
  Object.assign(reasonForm, {
    code: '',
    name: '',
    type: 'loss',
    category: '',
    description: '',
    solution: '',
    status: 'active'
  })
}

// 工具函数
const getTypeName = (type) => {
  const map = { profit: '盘盈', loss: '盘亏', common: '通用' }
  return map[type] || type
}

const getTypeTag = (type) => {
  const map = { profit: 'success', loss: 'danger', common: '' }
  return map[type] || ''
}

const getCategoryName = (category) => {
  const map = {
    management: '管理问题',
    system: '系统问题',
    human: '人为失误',
    quality: '商品质量',
    other: '其他'
  }
  return map[category] || category
}

// 初始化
pagination.total = reasons.value.length
</script>

<style scoped>
.reason-library-container {
  padding: 20px;
}

.header-card,
.filter-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.popular-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>

